package com.cl.util;

import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * 公共类封装有http请求等。
 * @author chenlu
 * @date 2018-3-14 上午9:39:08
 */
public class YZJHttpUtils {
	private static Logger logger = LoggerFactory.getLogger(YZJHttpUtils.class);
	static int HTTP_OK = 200;
	/**
	 * post方法
	 * @param url 地址
	 * @param params 参数
	 * @return
	 */
	public static String sendPost(String url, List<NameValuePair> params) throws Exception{
		HttpUriRequest httpPost = null;
		if(null != params) {
			httpPost = RequestBuilder
					.post()
					.addHeader("Content-Type",
							ContentType.APPLICATION_FORM_URLENCODED.toString())
					.setEntity(new UrlEncodedFormEntity(params,"UTF-8"))
					.setUri(url).build();
		} else {
			httpPost = RequestBuilder
					.post()
					.addHeader("Content-Type",
							ContentType.APPLICATION_FORM_URLENCODED.toString())
					.setUri(url).build();
		}
		return sendHttpRequest(httpPost);
	}
	
	
	public static String sendHttpRequest(HttpUriRequest httpRequest) throws Exception{
		HttpClient httpClient = HttpClients.createDefault();
		HttpResponse httpResponse = httpClient.execute(httpRequest);
		if (isRequestSuccessful(httpResponse)) {
			HttpEntity httpEntity = httpResponse.getEntity();
			String response = EntityUtils.toString(httpEntity, "utf-8");
			logger.info("http response", response); 
			return response;
		} else {
			return "错误的返回，"+httpResponse.toString();
		}
	}

	private static boolean isRequestSuccessful(HttpResponse httpResponse) {
		logger.info("response code：{}", httpResponse.getStatusLine().getStatusCode());
		return httpResponse.getStatusLine().getStatusCode() == HTTP_OK;
	}
	
}
